package com.astoolkit.workflow.xmlmapping
{
	import com.astoolkit.workflow.BasePipelineTask;
	
	import memorphic.xpath.XPathQuery;
	
	import mx.core.ClassFactory;
	import mx.core.IFactory;
	import mx.rpc.Fault;
	
	public class ReadXPathValue extends BasePipelineTask
	{
		public var path : String;
		public var xml : XML;
		public var ignoreNamespaces : Boolean;
		
		public var outputType : IFactory = new ClassFactory( XMLList );
		
		override public function begin(inRetain:Boolean=false):void
		{
			try
			{
				if( !xml )
					xml = _pipelineData;
				var query : XPathQuery = new XPathQuery( path );
				if( ignoreNamespaces )
				{
					query.context.openAllNamespaces = true;
				}
				else
				{
					var nss : Array = xml.namespaceDeclarations();
					for( var i  : int = 0; i < nss.length; i++ )
					{
						query.context.namespaces[ "ns" + i ] = nss[i].toString();
					}
				}
				var output : XMLList = query.exec( xml);
				switch( ClassFactory( outputType ).generator )
				{
					case String :
						_pipelineData = output.toString();
						break
					default : 
						_pipelineData = output;
				}
				complete();
			}
			catch( e : Error )
			{
				fail( e.message, new Fault( e.errorID.toString(), e.message, e.getStackTrace() ) );
			}
		}
	}
}